import * as React from 'react';
import { Modal } from 'office-ui-fabric-react/lib/Modal';
import { DefaultButton, PrimaryButton } from 'office-ui-fabric-react/lib/Button';
import Paragraph from './Paragraph';
import { documentGet } from '../../services/documentAssistant';
import { parse } from 'querystring'
import { Icon } from 'office-ui-fabric-react';
import TagClose from '../../components/TagClose';

interface Props {
  onChange?: Function
  location?: any
  id: string
  type: '1' | '2' | '3';
}

export default class ParagraphsSelect extends React.Component<Props,
  {
    // type?: '1' | '2' | '3';
    showModal: boolean;
    showALl: boolean;
    paragraphs: any[],
    checkedParagraphsId: any[],
    checkedParagraphs: any[],
    openedParagraphsId: any[],
  }
  > {
  constructor(props: Props) {
    super(props);
    this.state = {
      showModal: false,
      showALl: false,
      paragraphs: [],
      openedParagraphsId: [props.id],
      checkedParagraphs: [],
      checkedParagraphsId: [props.id], //把当前段落的id 默认选中
      // checkedItems: []
    };
  }

  // 获取所有的内容
  // 需要设置获取的类型 1,2，3
  // 获取当前段落的 id

  componentDidMount() {
    const { id, type } = this.props
    documentGet({
      id: id,
      type: type // TODO
    }).then(
      res => {
        console.info(res)
        this.setState({
          paragraphs: res.data
        }, this.handleCheck) // fix 第一条选中的数据
      }
    )
  }

  handleParagraphCheck = (item) => {
    let { checkedParagraphsId } = this.state
    const { id } = item
    if (this.checkSelected(id)) {
      checkedParagraphsId = checkedParagraphsId.filter(itemId => itemId !== id)
    } else {
      checkedParagraphsId.unshift(id)
    }

    this.setState({
      checkedParagraphsId
    }, this.handleCheck)
    console.info('id ', checkedParagraphsId)
  }

  checkSelected = (id) => {
    const { checkedParagraphsId } = this.state
    if (checkedParagraphsId.indexOf(id) < 0) {
      return false
    }
    return true
  }

  handleCheck = () => { // 获取footer选择的数据 按选择的先后排序
    const { checkedParagraphsId, paragraphs } = this.state
    const { type } = this.props

    const checkedItems = paragraphs.filter(
      item => checkedParagraphsId.indexOf(item.id) > -1
    ).sort(
      (a, b) => checkedParagraphsId.indexOf(a.id) - checkedParagraphsId.indexOf(b.id)
    )
    if (checkedItems) {
      const checkedParagraphs = checkedItems.map(item => {
        return {
          id: item.id,
          title: type === '3' ? item.content.slice(0, 20) : item.title // 片段的title 自己截取
        }
      })
      this.setState({
        checkedParagraphs
      })
    }

    // this.props.onChange(checkedParagraphsId)// 传到外部组件  // 把选择段落Id传到外部组件
  }

  expandAll = () => {
    let openedParagraphsId = []
    const { paragraphs } = this.state
    openedParagraphsId = paragraphs.map(
      item => item.id
    )
    this.setState({
      openedParagraphsId,
      showALl: true
    })
  }

  CallapseAll = () => {
    this.setState({
      openedParagraphsId: [],
      showALl: false
    })
  }

  handleSwitch = (id) => {
    let { openedParagraphsId } = this.state

    if (this.checkIsOpen(id)) {
      openedParagraphsId = openedParagraphsId.filter(itemId => itemId !== id)
    } else {
      openedParagraphsId.push(id)
    }

    this.setState({
      openedParagraphsId
    })
  }

  checkIsOpen = (id) => {
    const { openedParagraphsId } = this.state
    if (openedParagraphsId.indexOf(id) > -1) {
      return true
    } else {
      return false
    }
  }

  triggerShowAll = () => {
    const { showALl } = this.state
    this.setState({
      showALl: !showALl
    })
  }


  public render(): JSX.Element {

    const { paragraphs, showALl, checkedParagraphs } = this.state
    const { type, id } = this.props
    const typeMap = {
      1: '全文',
      2: '章节',
      3: '片段'
    }

    if (type === '1' && paragraphs.length) {
      const selectItem = paragraphs.find((item) => {
        return item.id === id;
      })
      return (
        <div className="" style={{
          marginTop: '40px'
        }}>
          <div className="view-header">
            <div className="title">
              全文预览
            </div>
          </div>
          <div className="container" style={{ backgroundColor: "#fff" }}>
            <h2 className="paragraph-title">{selectItem.title}</h2>
            <div dangerouslySetInnerHTML={{ __html: selectItem.content }}></div>
          </div>
        </div>
      )
    }

    return (
      <div className="view-page">
        <div className="view-header">
          <div className="title">
            {/* 章节预览 */}
            {typeMap[type]}预览
            <div className="pull-right">
              {
                showALl ? (
                  <span className="button" onClick={this.CallapseAll}>
                    {/* <Icon iconName="ChevronUpMed" className="view-icon" />收起全部 */}
                    <img src="/assets/callapse.svg" alt="收起全部" className="view-icon" />
                    收起全部
                   </span>
                ) : (
                    <span className="button" onClick={this.expandAll}>
                      <img src="/assets/expand.svg" alt="收起全部" className="view-icon" />
                      {/* <Icon iconName="ChevronDownMed" className="view-icon" /> */}
                      预览全部
                    </span>
                  )
              }
            </div>
          </div>
        </div>

        {
          paragraphs.map(item => {
            // console.info('段落', item)
            return <Paragraph
              key={item.id}
              onClick={() => this.handleParagraphCheck(item)}
              onSwitch={() => this.handleSwitch(item.id)}
              isOpen={this.checkIsOpen(item.id)}
              type={type}
              title={item.title}
              content={item.content}
              active={this.checkSelected(item.id)}
            />
          })
        }

        <div className="view-footer box-shadow-dark">
          <div className="label">
            已选择 {checkedParagraphs.length} 项 &nbsp;&nbsp;
          </div>
          <div className="content">
            {
              checkedParagraphs.map(item => {
                return <TagClose key={item.id} title={item.title} onRemove={() => { this.handleParagraphCheck(item) }} />
              })
            }
          </div>
          <PrimaryButton className="pull-right" disabled={checkedParagraphs.length < 1} onClick={this.insert} text="使用" />
        </div>
      </div>
    );
  }

  private insert = (): void => {
    const { checkedParagraphsId, paragraphs } = this.state
    // 根据id 获取文本
    const { type } = this.props
    const items = paragraphs.filter(
      item => checkedParagraphsId.indexOf(item.id) > -1
    )

    let html
    html = items.map(
      item => {
        if (type === '3') {
          return item.content + '<br />'
        } else if (type === '1') {
          return '<h1>' + item.title + '</h1>' + item.content
        } else if (type === '2') {
          return '<h3>' + item.title + '</h3>' + item.content
        }
      }
    )
    html = '<div>' + html.join('') + '</div>'

    Office.context.ui.messageParent(html);
  };

}
